/*
 *  Copyright 2010 asustatil.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package edu.upf.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;

/**
 *
 * @author asustatil
 */
public class NetInfo {

    private String ipAddr;
    private static NetInfo netInfo;
    private LogSystem log;

    private NetInfo() {
        try {
            log = new LogSystem(this.getClass());
            URL autoIP;
            BufferedReader in = null;
            autoIP = new URL("http://www.whatismyip.com/automation/n09230945.asp");
            in = new BufferedReader(new InputStreamReader(autoIP.openStream()));
            ipAddr = (in.readLine()).trim();
            log.addInfoLog("Public IP address detected: " + ipAddr);
        } catch (IOException ex) {
            ipAddr = getFirstNonLoopbackAddress();
            log.addDebugLog("Public IP  detection failed, local IP"+ipAddr);
        }
    }

    public static synchronized NetInfo getInstance(){
        if (netInfo == null) {
            netInfo = new NetInfo();
        }
        return netInfo;
    }

    public String getIP(){
        return ipAddr;
    }

    private String getFirstNonLoopbackAddress() {
        try {
            Enumeration en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface i = (NetworkInterface) en.nextElement();
                for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
                    InetAddress addr = (InetAddress) en2.nextElement();
                    if (!addr.isLoopbackAddress()) {
                        if (addr instanceof Inet4Address) {
                            return addr.getHostAddress();
                        }
                    }
                }
            }
            return null;
        } catch (SocketException ex) {
            log.addInfoLog("Failed to get local IP address");
            return null;
        }
    }

}
